import useUserStore from '@/store/useUserStore'
import { deepMerge } from '@/utils'
import { CAxios } from './axios'
import type { AxiosInterceptor, CreateAxiosOptions } from '#/axios'
import { message } from 'antd'

const interceptor: AxiosInterceptor = {
  requestInterceptors(config) {
    const token = useUserStore.getState().token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  responseInterceptors(res) {
    if (!res.data.success) {
      throw res.data.message
    }
    return res
  },
  responseInterceptorsCatch(error) {
    message.error(error as unknown as string)
  }
}

const createAxios = (options?: Partial<CreateAxiosOptions>) => {
  return new CAxios(
    deepMerge(
      {
        timeout: 6000,
        interceptor,
        headers: {
          'Content-Type': 'application/json',
          Accept: '*/*'
        }
      },
      options || {}
    )
  )
}
const request = createAxios()

export default request
